<?php

declare(strict_types=1);

namespace Reezy\APISign;

use Psr\Http\Message\ServerRequestInterface;
use function config;

class APISignManager
{
    private $map = [];
    private $config;
    private $headerAccessKey;

    public function __construct()
    {
        $this->config = config("api_sign", []);
        $this->headerAccessKey = $this->config['header_keys']['access_key'] ?? 'x-sign-key';
    }

    public function get(string $name): APISign
    {
        if (isset($this->map[$name])) {
            return $this->map[$name];
        }
        return $this->map[$name] = new APISign($name, $this->config[$name] ?? [], $this->config['header_keys'] ?? []);
    }

    public function check(ServerRequestInterface $request)
    {
        $name = $request->getHeaderLine($this->headerAccessKey) ?: $request->getQueryParams()[$this->headerAccessKey] ?? '';
        if (empty($name)) {
            throw new APISignException('no given sign checker');
        }
        $checker = $this->get($name);
        if ($checker == null) {
            throw new APISignException('no match sign checker');
        }
        $checker->check($request);
    }
}
